//
//  LBOSSService.m
//  app
//
//  Created by 杨庆人 on 16/8/8.
//  Copyright © 2016年 广东联结电子商务有限公司. All rights reserved.
//

#import "LBOSSService.h"
#import "LBOSSURL.h"
#import <MJExtension/MJExtension.h>
#import <OpenUDID/OpenUDID.h>
#import <LBCategory/LBCategory.h>
@implementation LBServiceOSSModel

@end


@implementation LBOSSService



+ (void)getOSSUploadDataWithFile:(NSData *)data
                        fileType:(LBServiceOSSCode)fileType
                     contentType:(NSString *)contentType
                   progressBlock:(void(^)(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))progressBlock
                   uploadSuccess:(void(^)(NSString * objectKey))uploadSuccess
                   getUrlSuccess:(void(^)(NSString * UrlString))getUrlSuccess
                         failure:(void(^)(NSError * error , NSString *message))failure{
    
    NSDictionary * dic = @{
                           @"fileType":[NSString stringWithFormat:@"%ld",(long)fileType]
                           };
    
    // 1.获取服务器token
    [LBService post:LBURL_OSSNew(URL_OSS_GetDataNew) params:dic completion:^(LBResponse *response) {
        if (response.succeed) {
            
            LBServiceOSSModel * serviceOSSModel = [LBServiceOSSModel mj_objectWithKeyValues:response.data];
            
            if (serviceOSSModel) {
                //用户UDID
                NSString * userId = [OpenUDID value];
                //当前时间戳
                NSTimeInterval timeInterval = [[NSDate date]timeIntervalSince1970];
                long long totalMilliseconds = timeInterval*1000 ;
                NSString * objectKey = [NSString stringWithFormat:@"%@2_%@_%llu",serviceOSSModel.dir,userId,totalMilliseconds];
                
                // 2.上传云服务器
                [LBOSSService uploadOSSWithData:data
                                   objectKey:objectKey
                                 AccessKeyId:serviceOSSModel.accessKeyId
                             AccessKeySecret:serviceOSSModel.accessKeySecret
                               SecurityToken:serviceOSSModel.securityToken
                                  bucketName:serviceOSSModel.bucket
                                 contentType:contentType
                                    endpoint:serviceOSSModel.endpoint
                progress:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
                    if (progressBlock) {
                        progressBlock ( bytesSent, totalBytesSent, totalBytesExpectedToSend);
                    }
                } Success:^(OSSAppendObjectResult *result) {
                    // 3.上传成功，回调objectKey
                    if (uploadSuccess) {
                        uploadSuccess(objectKey);
                    }

                    if (!getUrlSuccess) return ;
                    
                    // 4.使用objectKey，获取url
                    NSDictionary * dic = @{
                                           @"fileType":[NSString stringWithFormat:@"%ld",(long)fileType],
                                           @"key":objectKey
                                           };
                    
                    [LBService post:LBURL_OSSNew(URL_OSS_GetUrlString) params:dic completion:^(LBResponse *response) {
                        if (response.succeed) {
                            
                            // 5.获取成功，回调urlString
                            if (getUrlSuccess) {
                                getUrlSuccess(response.data);
                            }
                            NSLog(@"%@",response.data);
                        }else{
                            NSLog(@"获取图片url失败");
                        }
                    }];
                } failure:^(NSError *error) {
                    failure(error,error.description);
                }];
            }
        }else{
            failure(nil,response.message);
        }
    }];
}


/**
 
 * 通过objectKey获取url
 
 */

+ (void)getImageUrlWithObjectKey:(NSString *)objectKey
                         Success:(void(^)(NSString * imageUrl))success
                         failure:(void(^)(NSString * message))failure {
    
    NSDictionary * dic = @{
                           @"key":objectKey
                           };
    
    [LBService post:LBURL_OSSNew(URL_OSS_GetUrlString) params:dic completion:^(LBResponse *response) {
        if (response.succeed) {
            success(response.data);
            NSLog(@"%@",response.data);
        }else{
            failure(response.message);
        }
    }];
}

/**
 同步图片Token鉴黄
 
 @param objectKey
 @param success
 @param failure
 */
+ (void)syncPictureIdentificationYellowWithObjectKey:(NSString *)objectKey success:(void(^)())success failure:(void(^)(NSString * msg))failure {

    NSDictionary * dic = @{
                           @"tokenKey":objectKey
                           };
    
    [LBService post:LBURL_OSSNew(URL_OSS_SyncPictureYellow) params:dic completion:^(LBResponse *response) {
        if (response.succeed) {
            
            NSDictionary * dic = [response.data valueForKey:@"porn"];
            
            NSNumber * label = [dic valueForKey:@"label"];
            
            if (![[label stringValue] isEqualToString:@"1"]) {
                
                success();
            }
            else {
            
                failure(response.message);
            }
        }
        else {

            failure(response.message);
        }
    }];

}



/**
 文件预览(注：只支持doc和Excel文件预览)
 
 @param sign 签名
 @param suffix 后缀
 @param timestamp 时间戳
 @param url 文件路径
 @param success html内容
 @param failure
 */
+ (void)filePreviewWithSign:(NSString *)sign suffix:(NSString *)suffix timestamp:(NSString *)timestamp url:(NSString *)url success:(void(^)(NSString * result))success failure:(void(^)(NSString * message))failure {
    NSDictionary * dic = @{
                           @"sign":sign,
                           @"suffix":suffix,
                           @"timestamp":timestamp,
                           @"url":url
                           };
    
    [LBService get:LBURL_OSSNew(URL_OSS_FilePreview) params:dic completion:^(LBResponse *response) {
        if (response.succeed) {
            
            success([response.data objectForKey:@"result"]);
        }
        else {
        
            failure(response.message);
        }
    }];

}

+(void)uploadOSSWithData:(NSData *)data
               objectKey:(NSString *)dataName
             AccessKeyId:(NSString *)AccessKeyId
         AccessKeySecret:(NSString *)AccessKeySecret
           SecurityToken:(NSString *)SecurityToken
              bucketName:(NSString *)bucketName
             contentType:(NSString *)contentType
                endpoint:(NSString *)endpoint
                progress:(OSSNetworkingUploadProgressBlock )progressBlock
                 Success:(void(^)(OSSAppendObjectResult * result))success
                 failure:(void(^)(NSError * error))failure{
    
    
    id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:AccessKeyId secretKeyId:AccessKeySecret securityToken:SecurityToken];
    
    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    conf.maxRetryCount = 3; // 网络请求遇到异常失败后的重试次数
    conf.timeoutIntervalForRequest = 30; // 网络请求的超时时间
    conf.timeoutIntervalForResource = 24 * 60 * 60; // 允许资源传输的最长时间
    
    OSSClient * client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential clientConfiguration:conf];
    
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.bucketName = bucketName;
    put.objectKey = dataName;
    put.contentType = contentType;
    
    put.uploadingData = data;
    
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        
        progressBlock (bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    
    OSSTask * putTask = [client putObject:put];
    
    [putTask continueWithBlock:^id(OSSTask *task) {
        
        task = [client presignPublicURLWithBucketName:bucketName
                                        withObjectKey:dataName];
        if (!task.error) {
            OSSAppendObjectResult * result = task.result;
            success(result);
        } else {
            failure(task.error);
        }
        return nil;
    }];
}


@end
